import {baseUploadUrl, baseUrl} from '@/config/env';
import {getStore} from "../utils/store";

export default (app, option = {}) => {
    let optionObj = import.meta.glob(`../option/**/**`)[`../option/${option.name}.js`]
    let apiObj = import.meta.glob(`../api/**/**`)[`../api/${option.name}.js`]

    // 默认的接口
    let defaultApiObj = import.meta.glob(`../crud/api/**`)[`../crud/api/crudApi.js`]
    // 默认的表格配置
    let defaultOption = import.meta.glob(`../crud/**`)[`../crud/defaultOption.js`]
    if (!apiObj) {
        apiObj = defaultApiObj;
    }

    let mixins = {
        data() {
            return {
                key: Math.random(),
                // 接口前缀
                data: [],
                form: {},
                params: {},
                option: {},
                api: {},
                // 组件传的参数
                // crudOptionProps: {},
                permissions: [],
                loading: false,
                page: {},

            }
        },

        created() {
            console.log("2222",this.crudOptionProps)
            this.option = option;
            console.log("option",this.option)

            this.option = this.optionObjAssignUtils(option, this.crudOptionProps)
            let p1 = apiObj().then(apiObjMode => {
                this.api = apiObjMode;
            });


            let p3 = undefined;
            let p2 = defaultOption().then(defaultOptionMode => {
                this.option = this.optionObjAssignUtils(defaultOptionMode.default(this), this.option);
            }).then(() => {

            });
            if (optionObj) {
                p3 = optionObj().then(optionObjMode => {
                    this.option = this.optionObjAssignUtils(optionObjMode.default(this), this.option)
                });
            }

            console.log(this.option)
            Promise.all([p1, p2, p3]).then(() => {
                this.key = Math.random()
                let apiOption = this.option.apiOption;
                let tableOption = this.option.tableOption;
                let uploadOpt = this.option.uploadOpt;
                // 默认值设置
                this.setDefaultOption(this.option)
                console.log(this.option)

                this.getList();

            })


        },
        computed: {


            bindVal() {

                console.log("bindVal")
                return {
                    ref: 'crud',
                    key: this.key,
                    option: this.option.tableOption,
                    data: this.data,
                    tableLoading: this.loading
                }
            },
            onEvent() {
                return {
                    'size-change': this.sizeChange,
                    'current-change': this.currentChange,
                    'row-save': this.rowSave,
                    'row-update': this.rowUpdate,
                    'row-del': this.rowDel,
                    'refresh-change': this.refreshChange,
                    'search-reset': this.searchChange,
                    'search-change': this.searchChange,
                    'change': this.selectChange,

                }
            },
            rowKey() {
                return option.rowKey || 'id'
            }
        },
        methods: {
            // 对象合并
            optionObjAssignUtils(target, source) {

                // 由于属性对象名称一样,后面的将会覆盖前面的, 所以如果二级属性为对象的话,则会覆盖,不会合并,特此写这个方法
                let apiOption = Object.assign((target.apiOption || {}), (source.apiOption || {}))
                let tableOption = Object.assign((target.tableOption || {}), (source.tableOption || {}))

                let uploadOpt = Object.assign((target.uploadOpt || {}), (source.uploadOpt || {}))
                let permissionOption = Object.assign((target.permissionOption || {}), (source.permissionOption || {}))

                let option = Object.assign(target, source);
                option.apiOption = apiOption;
                option.tableOption = tableOption;
                option.uploadOpt = uploadOpt;
                option.permissionOption = permissionOption
                return option;
            },
            // 表格字段处理
            setTableColumn() {


                let columns = this.option.tableOption.column;
                columns.forEach(item => {
                    item.overHidden = true;
                    //给列重新赋值
                    if (item.resetting) {
                        Object.keys(item.resetting()).forEach((it, index) => {
                            item[it] = Object.values(item.resetting())[index]
                        })
                    }

                    // 图片处理
                    if (item.type == 'image') {
                        item.type = 'upload'
                        if (!item.limit) {
                            item.limit = 1;
                        }
                        if (item.limit == 1) {
                            item.dataType = 'json';
                            item.listType = 'picture-img';
                        } else {
                            item.dataType = 'array';
                            item.listType = 'picture-card';
                        }
                        // 文件上传的配置
                        let uploadOpt = this.option.uploadOpt;
                        if (!item.action) {
                            item.action = uploadOpt.uploadUrl;
                        }
                        if (!item.action.startsWith("http")) {
                            item.action = baseUploadUrl + item.action;
                        }
                        item.action = item.action.replace("{imageClassify}", item.dictType)
                        item.accept = uploadOpt.imgAccept;
                        item.fileSize = uploadOpt.fileSize;
                        item.propsHttp = uploadOpt.propsHttp;

                    } else if (item.type == 'upload') {

                        // 文件上传
                        if (!item.limit) {
                            item.limit = 1;
                        }
                        // 文件上传的配置
                        let uploadOpt = this.option.uploadOpt;
                        if (!item.action) {
                            item.action = uploadOpt.uploadUrl;
                        }
                        if (!item.action.startsWith("http")) {
                            item.action = baseUploadUrl + item.action;
                        }
                        item.action = item.action.replace("{imageClassify}", item.dictType)
                        item.accept = uploadOpt.uploadAccept;
                        item.fileSize = uploadOpt.fileSize;
                        item.propsHttp = uploadOpt.propsHttp;
                    } else if (item.type == 'tree') {
                        // 树结构
                        item.checkStrictly = true;
                        if (item.dicUrl) {
                            if (item.dicUrl.substring(0, 4) != 'http') {
                                item.dicUrl = baseUrl + item.dicUrl
                            }
                        }


                        item.dicFormatter = (res) => {
                            item.dicData = this.dealTreeData(res.data);
                            item.dicData.forEach(item => {
                                item.label = item.name;
                            })
                        }
                        item.props = {
                            label: 'name'
                        }
                    } else if (item.type == 'dict') {
                        // 字典处理
                        // 字典的默认配置
                        let dictOpt = this.option.dictOpt;
                        if (!item.dicUrl) {
                            item.dicUrl = dictOpt.dicUrl;
                        }
                        if (!item.dicUrl.startsWith("http")) {
                            item.dicUrl = baseUrl + item.dicUrl;
                        }
                        console.log(item.dicUrl)
                        item.dicUrl = item.dicUrl.replace("{dictType}", item.dictType)
                        item.type = "select";
                        // item.html = true;
                        // item.formatter = (val, value, label) => {
                        //     // let newLabel = this.dictFormatterHandler(val, value, label,style);
                        //     // return newLabel;
                        //     return this.dictFormatter(item, val, value, label);
                        // }
                        //
                        // item.dicFormatter = (res) => {
                        //     let data = res.data;
                        //     data.forEach(ele => {
                        //         const label = ele.label;
                        //         let index = label.indexOf("(")
                        //         ele.label = label.substr(0, index);
                        //     })
                        //     return data;
                        // }

                    }
                    if (item.dictType) {
                        // 字典的默认配置
                        let dictOpt = this.option.dictOpt;
                        if (!item.dicUrl) {
                            item.dicUrl = dictOpt.dicUrl;
                        }
                        if (!item.dicUrl.startsWith("http")) {
                            item.dicUrl = baseUrl + item.dicUrl;
                        }
                        item.dicUrl = item.dicUrl.replace("{dictType}", item.dictType)

                    }
                    // 引用类型处理
                    if (item.type == 'quote') {
                        item.type = 'input'
                        if (item.disabled == undefined) {
                            item.disabled = true
                        }
                        item.formatter = (val, value, label) => {
                            return this.quoteFormatter(item, val, value, label);
                            // return val[item.quoteType]
                        }

                    }
                    // 给所有的dicUrl 增加baseUrl
                    if (item.dicUrl) {
                        if (!item.dicUrl.startsWith("http")) {
                            item.dicUrl = baseUrl + item.dicUrl;
                        }
                    }
                    // 校验规则
                    if (item.required) {
                        // 添加必填的参数
                        let rules = item.rules;
                        let requiredRule = {
                            required: true,
                            message: "请输入" + item.label,
                            trigger: "blur"
                        }
                        if (null == rules || rules.length == 0) {
                            rules = [];
                            rules.push(requiredRule);
                        } else {
                            let reRequ = rules.filter(r => r.required == true);
                            if (null == reRequ) {
                                rules.push(requiredRule);
                            }
                        }
                        item.rules = rules;
                    }

                })
                this.option.tableOption.column = columns;
            },

            // 设置默认的option
            setDefaultOption(option) {
                let apiOption = option.apiOption;

                console.log(this.option.functionParams)

                if (this.option.functionTarget) {

                    let serverlessUrl = apiOption.serverlessUrl;
                    let serverlessApi = apiOption.serverlessApi;


                    this.option.listApi = serverlessApi;
                    this.option.listUrl = {
                        url: serverlessUrl,
                        functionMethod: 'get',
                        functionTarget: this.option.functionTarget
                    };
                    this.option.addApi = serverlessApi;
                    this.option.addUrl = {
                        url: serverlessUrl,
                        functionMethod: 'save',
                        functionTarget: this.option.functionTarget
                    };
                    ;

                    this.option.delApi = serverlessApi;
                    this.option.delUrl = {
                        url: serverlessUrl,
                        functionMethod: 'delete',
                        functionTarget: this.option.functionTarget
                    };
                    ;
                    this.option.updateApi = serverlessApi;
                    this.option.updateUrl = {
                        url: serverlessUrl,
                        functionMethod: 'update',
                        functionTarget: this.option.functionTarget
                    };
                    ;


                } else {
                    if (this.validatenull(this.option.listApi)) {
                        this.option.listApi = apiOption.listApi;
                    }
                    if (this.validatenull(this.option.listUrl)) {
                        this.option.listUrl = this.option.apiPrefix + apiOption.listUrl;
                    }
                    if (this.validatenull(this.option.addApi)) {
                        this.option.addApi = apiOption.addApi;
                    }
                    if (this.validatenull(this.option.addUrl)) {
                        this.option.addUrl = this.option.apiPrefix + apiOption.addUrl;
                    }

                    if (this.validatenull(this.option.delApi)) {
                        this.option.delApi = apiOption.delApi;
                    }
                    if (this.validatenull(this.option.delUrl)) {
                        this.option.delUrl = this.option.apiPrefix + apiOption.delUrl;
                    }
                    if (this.validatenull(this.option.updateApi)) {
                        this.option.updateApi = apiOption.updateApi;
                    }
                    if (this.validatenull(this.option.updateUrl)) {
                        this.option.updateUrl = this.option.apiPrefix + apiOption.updateUrl;
                    }

                }


                // 权限配置
                let permissionOption = this.option.permissionOption
                this.permissions = getStore({name: 'permission'}) || [];

                if (permissionOption.enable) {
                    let tableOption = this.option.tableOption


                    let name = this.option.name.replace("/", ":");
                    let addBtnPer = name + permissionOption.addBtnPer;
                    let editBtnPer = name + permissionOption.editBtnPer;
                    let delBtnPer = name + permissionOption.delBtnPer;
                    let viewBtnPer = name + permissionOption.viewBtnPer;


                    let addBtn = permissionOption.addBtn;
                    let editBtn = permissionOption.editBtn;
                    let delBtn = permissionOption.delBtn;
                    let viewBtn = permissionOption.viewBtn;
                    tableOption.addBtn = addBtn;
                    tableOption.editBtn = editBtn;
                    tableOption.delBtn = delBtn;
                    tableOption.viewBtn = viewBtn;

                    if (this.permissions.includes(addBtnPer)) {
                        tableOption.addBtn = true;
                    }
                    if (this.permissions.includes(editBtnPer)) {
                        console.log("222")
                        tableOption.editBtn = true;
                    }
                    if (this.permissions.includes(delBtnPer)) {
                        tableOption.delBtn = true;
                    }
                    if (this.permissions.includes(viewBtnPer)) {
                        tableOption.viewBtn = true;
                    }
                }

                console.log(this.option)
                this.setTableColumn();
            },


            getList() {
                const callback = () => {
                    this.loading = true
                    let pageParams = {}
                    pageParams[this.option.pageNumber || 'current'] = this.page.currentPage
                    pageParams[this.option.pageSize || 'size'] = this.page.pageSize
                    pageParams['param'] = this.params

                    // const data = Object.assign(pageParams, this.params)
                    const data = pageParams;
                    this.data = []
                    this.api[this.option.listApi || 'listApi'](this.option.listUrl, data).then(res => {
                        this.loading = false
                        console.log(res.data)
                        let data
                        if (option.res) {
                            data = this.option.res(res.data)
                        } else {
                            data = res.data.data
                        }
                        console.log(data)
                        console.log(this.option)

                        this.page.total = data[this.option.apiOption.total || 'total']
                        const result = data[this.option.apiOption.data || 'records']
                        this.data = result
                        if (this.listAfter) {
                            this.listAfter(data)
                        } else {
                            this.$message.success('获取成功')
                        }
                    })
                }
                if (this.listBefore) {
                    this.listBefore(this.params, this.form)
                }
                callback()
            },
            rowSave(row, done, loading) {

                const callback = () => {
                    delete this.form.params
                    this.api[this.option.addApi || 'addApi'](this.option.addUrl, this.form).then((data) => {
                        this.getList()
                        if (this.addAfter) {
                            this.addAfter(data)
                        } else {
                            this.$message.success('新增成功')
                        }
                        done()
                    }).catch(() => {
                        loading()
                    })
                }
                this.quoteHanlder(this.form)
                if (this.addBefore) {
                    this.addBefore(this.form)
                }
                callback()
            },
            rowUpdate(row, index, done, loading) {
                const callback = () => {
                    delete this.form.params
                    this.api[this.option.updateApi || 'updateApi'](this.option.updateUrl, this.form).then((data) => {
                        // this.api[option.updateApi || 'updateApi'](row[this.rowKey], this.form, index).then((data) => {
                        this.getList()
                        if (this.updateAfter) {
                            this.updateAfter(data)
                        } else {
                            this.$message.success('更新成功')
                        }
                        done()
                    }).catch(() => {
                        loading()
                    })
                }
                this.quoteHanlder(this.form)
                if (this.updateBefore) {
                    this.updateBefore(this.form)
                }
                callback()
            },
            rowDel(row, index) {
                const callback = () => {

                    this.$confirm(`此操作将永久删除序号【${index}】的数据, 是否继续?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.api[this.option.delApi || 'delApi'](this.option.delUrl, row[this.rowKey]).then((data) => {
                            // this.api[option.delApi || 'delApi'](row[this.rowKey], row).then((data) => {
                            this.getList()
                            if (this.delAfter) {
                                this.delAfter(data, row, index)
                            } else {
                                this.$message.success('删除成功')
                            }
                        })
                    })


                }
                if (this.delBefore) {
                    this.delBefore(row, index)
                }
                callback()
            },
            searchChange(params, done) {
                if (done) done()
                this.params = params
                this.page.currentPage = 1
                this.getList()
            },
            refreshChange() {
                this.getList()
            },
            sizeChange(val) {
                this.page.currentPage = 1
                this.page.pageSize = val
                this.getList()
            },
            currentChange(val) {
                this.page.currentPage = val
                this.getList()
            },
            dealTreeData(treeData) {
                const data = treeData.map((item) => ({
                    ...item,
                    value: item.id,
                    children: (item.children && item.children.length)
                        ? this.dealTreeData(item.children)
                        : null,
                }));
                return data;
            }, selectChange(e) {
                this.option.tableOption.column.forEach(item => {
                    if (item.quoteType) {
                        e[item.prop] = e[item.quoteType]
                    }
                })
            },
            // 引用处理
            quoteHanlder(form) {
                this.option.tableOption.column.forEach(item => {
                    if (item.quoteType) {
                        form[item.prop] = form["$" + item.quoteType]

                    }
                })
            },
            quoteFormatter(item, val, value, label) {
                return val[item.quoteType]

            }, dictFormatter(item, val, value, label) {
                let newLabel = this.dictFormatterHandler(val, value, label);
                return newLabel;
            }

        }
    }
    app.mixins = app.mixins || []
    app.mixins.push(mixins)
    return app
}
